package edu.ucsur.tp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import edu.ucsur.tp.beans.Usuario;
import edu.ucsur.tp.database.utils.MySqlDbConnection;

/**
 * Clase que maneja todo lo relacionado a la tabla usuario desde JPA.
 * 
 * @author Administrator
 *
 */
public class JpaUsuarioDAO implements UsuarioDAO {
  
  private EntityManagerFactory emFactory;
  private EntityManager manager = null;
   
  public JpaUsuarioDAO(EntityManagerFactory emFactory) {
    this.emFactory = emFactory;
  }

  @Override
  public List<Usuario> obtenerTodos() {
    try {
      manager = emFactory.createEntityManager();
      return manager.createNamedQuery("Usuario.findAll", Usuario.class).getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      manager.close();
    }
    return null;
  }

  @Override
  public Usuario obtener(String codigo) {
    try {
      manager = emFactory.createEntityManager();
      return manager.find(Usuario.class, codigo);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      manager.close();
    }
    return null;
  }

  @Override
  public void insertar(Usuario u) {
    EntityTransaction tx = null;
    try {
      manager = emFactory.createEntityManager();
      tx = manager.getTransaction(); 
      tx.begin();
      manager.persist(u);
      tx.commit();
    } catch (Exception ex) {
      tx.rollback();
      ex.printStackTrace();
    } finally {
      manager.close();
    }
  }

  @Override
  public void actualizar(Usuario u) {
    EntityTransaction tx = null;
    try {
      manager = emFactory.createEntityManager();
      tx.begin();
      manager.merge(u);
      tx.commit();
    } catch (Exception ex) {
      tx.rollback();
      ex.printStackTrace();
    } finally {
      manager.close();
    }
  }

  @Override
  public void eliminar(String codigo) {
    EntityTransaction tx = null;
    try {
      manager = emFactory.createEntityManager();
      Usuario u = manager.find(Usuario.class, codigo);
      if (u != null) {
        tx.begin();
        manager.remove(u);
        tx.commit();
      }
    } catch (Exception ex) {
      tx.rollback();
      ex.printStackTrace();
    } finally {
      manager.close();
    }
  }

}
